<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/22 0022
 * Time: 下午 4:50
 */
namespace app\admin\controller;

use app\admin\model\Letter;
use app\admin\model\SupervisionDiscuss;
use app\admin\model\SupervisionEstimate;
use app\admin\model\SupervisionSchedule;
use app\admin\model\SupervisionUsers;
use app\common\BaseHelper;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 督办
 * Class Supervision
 * @package app\admin\controller
 */
class Supervision extends Base{

    public function _initialize(){

        parent::_initialize();
        $this->searchFields = [
            'title' => [
                'label'     => '标题',
                'field'     => 'title',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
            'typeId' => [
                'label'     => '督办类型',
                'field'     => 'typeId',
                'type'      => 'select',
                'disabled'  => false,
                'condition' => '=',
                'data' => [
                    '0' => '所有',
                    '1' => '内部工作',
                    '2' => '信访工作'
                ]
            ],
            'schedule' => [
                'label'     => '督办进度',
                'field'     => 'schedule',
                'type'      => 'select',
                'disabled'  => false,
                'condition' => '=',
                'data' => [
                    '0' => '所有',
                    '1' => '未开始',
                    '2' => '进行中',
                    '3' => '已完成'
                ]
            ],
        ];
        $this->redirect = 'admin/supervision/index';
    }

    public function index(){
        $lgonUserId = session('ADMIN')->id;
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);
            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];
            $this->defaultWhere = ['createUser'=>$lgonUserId];
            $where = $this->getFilterWhere($request);
            if(isset($where['typeId']) && !empty($where['typeId'])){
                $typewhere['typeId'] = $where['typeId'];
                $stypewhere['s.typeId'] = $where['typeId'];
                unset($where['typeId']);
            }else{
                $typewhere = [];
                $stypewhere = [];
            }
            if(isset($where['schedule']) && !empty($where['schedule'])){
                $schedulewhere['schedule'] = $where['schedule'];
                $sschedulewhere['s.schedule'] = $where['schedule'];
                unset($where['schedule']);
            }else{
                $schedulewhere = [];
                $sschedulewhere = [];
            }
            if(isset($where['title']) && !empty($where['title'])){
                $titlewhere['title'] = $where['title'];
                $stitlewhere['s.title'] = $where['title'];
                unset($where['title']);
            }else{
                $titlewhere = [];
                $stitlewhere = [];
            }
            if($this->defaultWhere){
                $where = array_merge($where, $this->defaultWhere);
            }
            $field = 'id,title,createDate,typeId,schedule,createUser';
            $list1 = $model->where($where)->where($typewhere)->where($schedulewhere)->where($titlewhere)->field($field)->select();
            $join = [
                ['supervision s','s.id=a.supervisionId']
            ];
            $field = 's.id,s.title,s.createDate,s.typeId,s.schedule,s.createUser,a.user_id,a.supervisionId';
            $list2 = model('supervision_users')->alias('a')->where('a.user_id',$lgonUserId)->where($stypewhere)->where($sschedulewhere)->where($stitlewhere)->join($join)->select();
            $list = array_merge($list1,$list2);
            $listarr = [];
            foreach ($list as $v){
                array_push($listarr,$v['id']);
            }
            $list = array_unique($listarr);
            $res = [];
            if($list){
                $Supervision = \app\admin\model\Supervision::where('id','in',$list)->order($order)->limit($start, $length)->select();
                foreach ($Supervision as &$item) {

                    $name = \app\admin\model\User::where('id',$item['createUser'])->value('p_name');
                    $item['name'] = $name;
                    $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$item['id'],'user_id'=>$lgonUserId])->find();
                    if($SupervisionUsers){
                        $item['showhandle'] = 1;
                        $item['showjiaoliu'] = 1;
                    }else{
                        $item['showhandle'] = 0;
                        $item['showjiaoliu'] = 0;
                    }
                    if($item['createUser'] == $lgonUserId){

                        //显示编辑
                        $item['showedit'] = 1;
                        $item['showdel'] = 1;
                        $item['showpingjia'] = 1;
                        $item['showhandle'] = 1;
                        $item['showjiaoliu'] = 1;
                    }else{
                        $item['showedit'] = 0;
                        $item['showdel'] = 0;
                        $item['showpingjia'] = 0;
                    }

                    if($item['showhandle'] == 1 || $item['showedit'] == 1){
                        array_push($res,$item);
                    }


                }
            }
            $list = array_merge($list1,$list2);
            $listarr = [];
            foreach ($list as $v){
                array_push($listarr,$v['id']);
            }
            $list = array_unique($listarr);
            $ress = [];
            if($list){
                $Supervision = \app\admin\model\Supervision::all($list);
                foreach ($Supervision as &$item) {

                    $name = \app\admin\model\User::where('id',$item['createUser'])->value('p_name');
                    $item['name'] = $name;
                    $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$item['id'],'user_id'=>$lgonUserId])->find();
                    if($SupervisionUsers){
                        $item['showhandle'] = 1;
                        $item['showjiaoliu'] = 1;
                    }else{
                        $item['showhandle'] = 0;
                        $item['showjiaoliu'] = 0;
                    }
                    if($item['createUser'] == $lgonUserId){

                        //显示编辑
                        $item['showedit'] = 1;
                        $item['showdel'] = 1;
                        $item['showpingjia'] = 1;
                        $item['showhandle'] = 1;
                        $item['showjiaoliu'] = 1;
                    }else{
                        $item['showedit'] = 0;
                        $item['showdel'] = 0;
                        $item['showpingjia'] = 0;
                    }
                    if($item['showhandle'] == 1 || $item['showedit'] == 1){
                        array_push($ress,$item);
                    }
                }
            }
            $count = count($ress);
            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $res,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }
        return parent::index();
    }

    public function add(){
        $Department = \app\admin\model\Department::where('status',1)->select();
        $Letter = Letter::where('status',1)->order('createDate DESC')->select();
        return $this->fetch('',[
            'department' => $Department,
            'letter' => $Letter
        ]);
    }
    //添加督办
    public function addPost(Request $request){
        $loginUserId = session('ADMIN')->id;
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['typeId'])){
                return $this->error('参数错误');
            }else{
                if($param['typeId'] != 1 && $param['typeId'] != 2){
                    return $this->error('参数错误');
                }
                if($param['typeId'] == 2){
                    if(empty($param['letterId'])){
                        return $this->error('信访工作必须选择信访件');
                    }
                }
            }
            if(empty($param['personIds'])){
                return $this->error('督办人不能为空');
            }
            Db::startTrans();
            try{
                $Supervision = new \app\admin\model\Supervision();
                $id = BaseHelper::getUUID();
                $Supervision->id = $id;
                $Supervision->typeId = $param['typeId'];
                $Supervision->title = $param['title'];
                $Supervision->letterId = $param['letterId'];
                $Supervision->urgency_degree = $param['urgency_degree'];
                $Supervision->content = $param['introduction'];
                $Supervision->complete_time = $param['complete_time'];
                $Supervision->createUser = $loginUserId;
                $Supervision->save();
                $this->insertsupervisionusers($param['personIds'],$id);
                if(isset($param['imgIds']) && !empty($param['imgIds'])){
                    $this->insertFiles($param['imgIds'],$id);
                }
                if($param['typeId'] == 2){
                    //信访督办，需要改变信访件的状态
                    Letter::updateSattus($param['letterId']);
                }
                //向督办人发短信(加入到队列)
                $data = [];
                $data['title'] = $param['title'];
                $data['complete_time'] = $param['complete_time'];
                if($param['urgency_degree'] == 1){
                    $data['urgency_degree'] = '一般';
                }elseif ($param['urgency_degree'] == 2){
                    $data['urgency_degree'] = '紧急';
                }else{
                    $data['urgency_degree'] = '加急';
                }
                $Supervision = new \app\admin\service\Supervision();
                $Supervision->senMsg($data,$param['personIds']);
                Db::commit();
                return $this->success('添加成功',$this->redirect);
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }


    public function edit(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('参数错误');
        }
        $Supervision = \app\admin\model\Supervision::get($param['id']);
        $Department = \app\admin\model\Department::where('status',1)->select();
        $Supervision['lettername'] = '';
        if($Supervision->typeId == 2){
            $Letter = Letter::get($Supervision->letterId);
            $Supervision['lettername'] = $Letter['title'];
        }
        $Supervision['date'] = date('Y-m-d',strtotime($Supervision->complete_time));
        $SupervisionUsers = SupervisionUsers::where('supervisionId',$Supervision->id)->select();
        $list = [];
        foreach ($SupervisionUsers as $v){
            array_push($list,$v['user_id']);
        }
        if($list){
            $User = \app\admin\model\User::all($list);
        }else{
            $User = NULL;
        }
        $Image = \app\admin\model\Image::where('relatedId',$Supervision->id)->select();

        if($Image){
            $this->assign('imgfiles',$Image);
        }else{
            $this->assign('imgfiles',null);
        }

        return $this->fetch('',[
            'info' => $Supervision,
            'department' => $Department,
            'letter' => isset($Letter)?$Letter:null,
            'user' => $User
        ]);

    }

    //编辑督办
    public function editPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('缺少参数');
            }
            if(empty($param['personIds'])){
                return $this->error('督办人不能为空');
            }
            Db::startTrans();
            try{
                $Supervision = \app\admin\model\Supervision::get($param['id']);
                if($Supervision->schedule == 3){

                    return json(['message'=>'该督办已经结束，不可编辑','code'=>'0']);
                }

                $Supervision->title = $param['title'];
                $Supervision->urgency_degree = $param['urgency_degree'];
                $Supervision->content = $param['introduction'];
                $Supervision->complete_time = $param['complete_time'];
                $Supervision->save();
                $data = [];
                $data['id'] = $param['id'];
                $data['title'] = $param['title'];
                $data['complete_time'] = $param['complete_time'];
                if($param['urgency_degree'] == 1){
                    $data['urgency_degree'] = '一般';
                }elseif ($param['urgency_degree'] == 2){
                    $data['urgency_degree'] = '紧急';
                }else{
                    $data['urgency_degree'] = '加急';
                }
                $this->editsupervisionusers($param['personIds'],$data);
                if(isset($param['imgIds']) && !empty($param['imgIds'])){
                    $this->editFiles($param['imgIds'],$param['id']);
                }
                Db::commit();
                return $this->success('修改成功',$this->redirect);
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }

    //删除督办
    public function delete(Request $request){
        $loginUserId = session('ADMIN')->id;
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('缺少参数');
            }
            Db::startTrans();
            try{
                $Supervision = \app\admin\model\Supervision::get($param['id']);
                if($Supervision->createUser == $loginUserId){
                    if($Supervision->schedule != 1){
                        return $this->error('已经开始办理，不能删除');
                    }else{
                        $Supervision->delete();
                        //删除督办人
                        SupervisionUsers::where('supervisionId',$Supervision->id)->delete();
                        //删除附件
                        $filescount = \app\admin\model\Image::where('relatedId',$Supervision->id)->count();
                        if($filescount>0){
                            \app\admin\model\Image::where('relatedId',$Supervision->id)->delete();
                        }
                        //如果有交流删除交流
                        $SupervisionDiscuss = SupervisionDiscuss::where('supervisionId',$param['id'])->find();
                        if($SupervisionDiscuss){
                            SupervisionDiscuss::destroy(function ($query) use ($param){
                                $query->where('supervisionId','=',$param['id']);
                            });
                        }
                        //如果是信访督办，则要恢复信访件的正常状态
                        if($Supervision->typeId == 2){
                            $Letter = Letter::get($Supervision->letterId);
                            $Letter->status = 1;
                            $Letter->save();
                        }
                        Db::commit();
                        return $this->success('删除成功');
                    }
                }else{
                    return $this->error('用户异常');
                }

            }catch (Exception $ex){
                Db::rollback();
                return $this->error('删除失败');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    private function editsupervisionusers($param,$data){
        if(!is_array($param)){
            $res = [];
            $res[0] = $param;
            $param = $res;
        }
        $SupervisionUsersList = SupervisionUsers::where('supervisionId',$data['id'])->field('user_id')->select();
        $alreadylist = [];
        $dellist = [];
        foreach ($SupervisionUsersList as $v){
            $flag = true;
            for ($i=0;$i<count($param);$i++){
                if($param[$i] == $v['user_id']){
                    $flag = false;
                    break;
                }
            }
            if($flag){
                array_push($dellist,$v['user_id']);
            }
        }

        for($i=0;$i<count($param);$i++){
            $flag = true;
            foreach ($SupervisionUsersList as $v){
                if($param[$i] == $v['user_id']){
                    $flag = false;
                    break;
                }
            }
            if($flag){
                array_push($alreadylist,$param[$i]);
            }
        }
        if($dellist){
            SupervisionUsers::where('supervisionId',$data['id'])->where('user_id','in',$dellist)->delete();
        }
        if($alreadylist){
            $list = [];
            foreach (array_unique($alreadylist) as $v){
                $id = BaseHelper::getUUID();
                $user = \app\admin\model\User::where('id',$v)->field('departmentId')->find();
                array_push($list,['id'=>$id,'supervisionId'=>$data['id'],'user_id'=>$v,'dept_id'=>$user->departmentId]);
            }
            $SupervisionUsers = new SupervisionUsers();
            $SupervisionUsers->saveAll($list,false);
            //发短信（加入队列）
            $supserver = new \app\admin\service\Supervision();
            unset($data['id']);
            $supserver->senMsg($data,$alreadylist);
        }
    }

    private function insertsupervisionusers($param,$supervisionId){
        $SupervisionUsers = new SupervisionUsers();
        if(!is_array($param)){
            $res = [];
            $res[0] = $param;
            $param = $res;
        }
        $list = [];
        foreach (array_unique($param) as $v){
            $id = BaseHelper::getUUID();
            $user = \app\admin\model\User::where('id',$v)->field('departmentId')->find();
            array_push($list,['id'=>$id,'supervisionId'=>$supervisionId,'user_id'=>$v,'dept_id'=>$user->departmentId]);
        }
        $SupervisionUsers->saveAll($list,false);
    }

    private function editFiles($imgIds,$relatedId){
        if(!is_array($imgIds)){
            $res = [];
            $res[0] = $imgIds;
            $imgIds = $res;
        }
        $ImageList =  \app\admin\model\Image::where('relatedId',$relatedId)->field('id')->select();
        if($ImageList){
            $alreadylist = [];
            foreach ($ImageList as $v){
                array_push($alreadylist,$v['id']);
            }
            $reslist = array_diff($imgIds,$alreadylist);
            $list = [];
            if($reslist){
                foreach ($reslist as $v){
                    array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
                }
            }
        }else{
            $list = [];
            foreach ($imgIds as $v){
                array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
            }
        }
        if($list){
            $Image = new \app\admin\model\Image();
            $Image->isUpdate()->saveAll($list);
        }

    }

    private function insertFiles($imgIds,$relatedId){
        $Image = new \app\admin\model\Image();
        if(!is_array($imgIds)){
            $res = [];
            $res[0] = $imgIds;
            $imgIds = $res;
        }
        $list = [];
        foreach ($imgIds as $v){
            array_push($list,['id'=>$v,'relatedId'=>$relatedId]);
        }
        $Image->isUpdate()->saveAll($list);

    }

    /**
     * 督办办理
     * @param Request $request
     */
    public function handle(){
        $loginId = session('ADMIN')->id;
        $request = $this->request;
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('缺少参数');
        }
        $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$param['id'],'user_id'=>$loginId])->find();
        if($SupervisionUsers){
            $this->assign('showinsert',true);
        }else{
            $this->assign('showinsert',false);
        }
        $info = \app\admin\model\Supervision::get($param['id']);
        $name = \app\admin\model\User::where('id',$info->createUser)->value('p_name');
        $info['p_name'] = $name;
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        $list = SupervisionSchedule::where(['supervisionId'=>$info->id])->order('huibao_time DESC')->select();
        if($list){
            foreach ($list as &$v){
                $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$v['supervisionId'],'user_id'=>$loginId])->find();
                if(!$SupervisionUsers){
                    $v['showedit'] = false;
                }else{
                    if($v['user_id'] == $loginId){
                        $v['showedit'] = true;
                    }else{
                        $v['showedit'] = false;
                    }
                }
                $name = \app\admin\model\User::where('id',$v['user_id'])->value('p_name');
                $v['p_name'] = $name;
            }
        }


        return $this->fetch('',[
            'list' => $list,
            'info' => $info,
            'loginId' => $loginId,
            'title' => '督办办理',
            'bcn' => '<ul class="page-breadcrumb"><li><i class="icon-home"></i>&nbsp;<a href="'.url('admin/index/index').'">首页</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<a href="'.url('admin/supervision/index').'">督办</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<span>督办办理</span></li></ul>'
        ]);
    }

    //新增/修改办理
    public function addHandle(Request $request){
        if($request->isPost()){
            $param = $request->param();
            $supervisionId = $param['supervisionId'];
            $userId = $param['userId'];
            if(empty($supervisionId) || empty($userId)){
                return $this->error('参数错误');
            }
            if($param['speed']!=2 && $param['speed']!=3){
                return $this->error('参数错误');
            }
            Db::startTrans();
            try{
                $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$supervisionId,'user_id'=>$userId])->lock(true)->find();
                if(!$SupervisionUsers){
                    return $this->error('您不该办理该业务');
                }

                if(empty($param['id'])){
                    //新增
                    if($SupervisionUsers->speed == 3){
                        return $this->error('您已经完成该督办，不能新增');
                    }
                    $model = new SupervisionSchedule();
                    $id = BaseHelper::getUUID();
                    $model->id = $id;
                }else{
                    //修改
                    $model = SupervisionSchedule::get($param['id']);
                }

                $Supervision = \app\admin\model\Supervision::get($param['supervisionId']);
                if($Supervision->schedule == 3){
                    return $this->error('该督办已经结束');
                }

                $model->supervisionId = $supervisionId;
                $model->user_id = $userId;
                $model->content = $param['content'];
                $model->s_speed = $param['speed'];
                $model->huibao_time = date('Y-m-d H:i',time());
                $model->save();
                $SupervisionUsers->speed = $param['speed'];
                $SupervisionUsers->save();
                $allcount = SupervisionUsers::where(['supervisionId'=>$supervisionId])->count();
                $count = SupervisionUsers::where(['supervisionId'=>$supervisionId,'speed'=>3])->count();
                if($count<$allcount){
                    $Supervision->schedule = 2;
                }else{
                    $Supervision->schedule = 3;
                    $Supervision->actual_time = date('Y-m-d H:i:s',time());
                }
                $Supervision->save();
                if($Supervision->typeId == 2){
                    $Letter = Letter::get($Supervision->letterId);
                    if($Supervision->schedule == 3){
                        $Letter->status = 4;
                        $Letter->save();
                    }
                }
                Db::commit();
                return $this->success('增加成功');
            }catch (Exception $ex){
                Db::rollback();
                return $this->error($ex->getMessage());
            }
        }else{
            return $this->error('非法请求');
        }
    }


    //删除督办办理
    public function delSchedule(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['sspeed'])){
                return $this->error('参数错误');
            }
            if($param['sspeed'] != 2 && $param['sspeed'] != 3){
                return $this->error('参数不合法');
            }
            Db::startTrans();
            try{
                $SupervisionSchedule = SupervisionSchedule::get($param['id']);
                $Supervision = \app\admin\model\Supervision::get($SupervisionSchedule->supervisionId);
                if($Supervision->schedule == 3){
                    return $this->error('该督办已经结束');
                }
                $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$Supervision->id,'user_id'=>$SupervisionSchedule->user_id])->find();
                if($SupervisionSchedule->s_speed == 3 && $param['sspeed'] == 3){
                    //如果该督办人已经完成督办 则需要修改督办人的完成状态
                    $SupervisionUsers->speed = 2;
                    $SupervisionUsers->save();
                }
                $SupervisionSchedule->delete();
                Db::commit();
                return $this->success('删除成功');
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('删除失败');
            }

        }else{
            return $this->error('非法请求');
        }
    }

    //督办交流
    public function discuss(){
        $loginId = session('ADMIN')->id;
        $request = $this->request;
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('缺少参数');
        }
        $info = \app\admin\model\Supervision::get($param['id']);
        $name = \app\admin\model\User::where('id',$info->createUser)->value('p_name');
        $info['p_name'] = $name;
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$param['id'],'user_id'=>$loginId])->find();
        if(!$SupervisionUsers){
            $this->assign('showinsert',false);
        }else{
            $this->assign('showinsert',true);
        }
        $SupervisionUsers = SupervisionUsers::where('supervisionId',$param['id'])->where('user_id','<>',$loginId)->select();
        $flag = true;
        if($loginId != $info->createUser){
            $this->assign('lideruser',$info);
        }else{
            $this->assign('showinsert',true);
            $this->assign('lideruser','');
            $flag = false;
        }
        foreach ($SupervisionUsers as &$v){
            $name = \app\admin\model\User::where('id',$v['user_id'])->value('p_name');
            $v['user_name'] = $name;
            if($v['user_id'] == $info['createUser']){
                $flag = false;
            }
        }




        $list = SupervisionDiscuss::where(['supervisionId'=>$info->id])->select();
        foreach ($list as &$v){
            $p_name = \app\admin\model\User::where('id',$v['user_id'])->value('p_name');
            $v['p_name'] = $p_name;
            $v['content'] = urldecode($v['content']);
            if($v['to_user_id']){
                $to_username = \app\admin\model\User::where('id',$v['to_user_id'])->value('p_name');
                $v['to_username'] = $to_username;
            }else{
                $v['to_username'] = '所有人';
            }
            if($v['user_id'] == $loginId){
                $v['isdel'] = true;
            }else{
                $v['isdel'] = false;
            }

        }

        return $this->fetch('',[
            'list' => $list,
            'info' => $info,
            'userlist' => $SupervisionUsers,
            'loginId' => $loginId,
            'title' => '督办交流',
            'flag' => $flag,
            'bcn' => '<ul class="page-breadcrumb"><li><i class="icon-home"></i>&nbsp;<a href="'.url('admin/index/index').'">首页</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<a href="'.url('admin/supervision/index').'">督办</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<span>督办交流</span></li></ul>'
        ]);
    }

    //交流提交
    public function discussPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['supervisionId']) || empty($param['userId'])){
                return $this->error('缺少参数');
            }
            $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$param['supervisionId'],'user_id'=>$param['userId']])->find();
            $Supervision = \app\admin\model\Supervision::get($param['supervisionId']);
            if(!$SupervisionUsers && $param['userId'] != $Supervision->createUser){
                return $this->error('您不是创建人，也不是督办人，不能交流');
            }
            $model = new SupervisionDiscuss();
            $id = BaseHelper::getUUID();
            if($param['toUser']){
                $is_all = 0;
            }else{
                $is_all = 1;
            }
            $model->id = $id;
            $model->is_all = $is_all;
            $model->supervisionId = $param['supervisionId'];
            $model->user_id = $param['userId'];
            $model->content = $param['content'];
            $model->to_user_id = $param['toUser'];
            if($model->save()){
                return $this->success('ok');
            }else{
                return $this->error('新增失败');
            }

        }else{
            return $this->error('非法请求');
        }
    }

    //督办交流删除
    public function delDiscuss(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['userid'])){
                return $this->error('缺少参数');
            }
            $SupervisionDiscuss = SupervisionDiscuss::get($param['id']);
            if($SupervisionDiscuss){
                if($SupervisionDiscuss->user_id == $param['userid']){
                    $res = SupervisionDiscuss::where('id',$param['id'])->delete();
                    if($res){
                        return $this->success('删除成功');
                    }else{
                        return $this->error('删除失败');
                    }
                }else{
                    return $this->error('用户信息异常');
                }

            }else{
                return $this->error('该交流不存在');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    //督办评价
    public function evaluate(){
        $loginId = session('ADMIN')->id;
        $request = $this->request;
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('缺少参数');
        }
        $info = \app\admin\model\Supervision::get($param['id']);
        $name = \app\admin\model\User::where('id',$info->createUser)->value('p_name');
        $info['p_name'] = $name;
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }

        $list = SupervisionEstimate::where(['supervisionId'=>$info->id])->select();
        foreach ($list as &$v){
            $p_name = \app\admin\model\User::where('id',$v['user_id'])->value('p_name');
            $v['p_name'] = $p_name;
        }

        return $this->fetch('',[
            'list' => $list,
            'info' => $info,
            'loginId' => $loginId,
            'title' => '督办评价',
            'bcn' => '<ul class="page-breadcrumb"><li><i class="icon-home"></i>&nbsp;<a href="'.url('admin/index/index').'">首页</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<a href="'.url('admin/supervision/index').'">督办</a></li>&nbsp;<li><i class="fa fa-angle-right"></i>&nbsp;<span>督办评价</span></li></ul>'
        ]);
    }

    public function evaluatePost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['supervisionId']) || empty($param['userId'])){
                return $this->error('缺少参数');
            }
            if($param['estimate']!=1 && $param['estimate']!=2 && $param['estimate']!=3){
                return $this->error('参数错误');
            }
            $Supervision = \app\admin\model\Supervision::get($param['supervisionId']);
            if(!$Supervision){
                return $this->error('该督办不存在');
            }
            if($Supervision->schedule!=3){
                return $this->error('督办进行中，暂时不能评价');
            }
            if($Supervision->createUser != $param['userId']){
                return $this->error('您不能评价该督办');
            }
            $SupervisionEstimate = SupervisionEstimate::where('supervisionId',$param['supervisionId'])->find();
            if(!$SupervisionEstimate){
                $model = new SupervisionEstimate();
                $id = BaseHelper::getUUID();

                $model->id = $id;
                $model->supervisionId = $param['supervisionId'];
                $model->user_id = $param['userId'];
                $model->estimate = $param['estimate'];
                $model->e_content = $param['content'];
                if($model->save()){
                    return $this->success('ok');
                }else{
                    return $this->error('新增失败');
                }
            }else{
                return $this->error('您已经评价过，不能新增');
            }


        }else{
            return $this->error('非法请求');
        }
    }

    //修改评价
    public function editevaluate(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['estimateId']) || empty($param['sid'])){
                return $this->error('缺少参数');
            }
            if($param['estimate']!=1 && $param['estimate']!=2 && $param['estimate']!=3){
                return $this->error('参数错误');
            }
            $Supervision = \app\admin\model\Supervision::get($param['sid']);
            if(!$Supervision){
                return $this->error('该督办不存在');
            }
            if($Supervision->schedule!=3){
                return $this->error('督办进行中，暂时不能评价');
            }
            if($Supervision->createUser != $param['user_id']){
                return $this->error('您不能修改该督办');
            }

            $model = SupervisionEstimate::get($param['estimateId']);
            if($model->estimate == 1){
                return $this->error('不能修改好评');
            }else{
                $model->estimate = $param['estimate'];
                $model->e_content = $param['content'];
                if($model->save()){
                    return $this->success('ok');
                }else{
                    return $this->error('修改失败');
                }

            }

        }else{
            return $this->error('非法请求');
        }
    }

    public function deluser_url(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['supid'])){
                return json(['message'=>'缺少参数','code'=>'0']);
            }
            $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$param['supid'],'user_id'=>$param['id']])->find();
            if($SupervisionUsers->speed == 1){
                return json(['message'=>'删除成功','code'=>'1']);
            }else{
                return json(['message'=>'此指派人已经开始督办，不能删除','code'=>'0']);
            }
        }else{
            return json(['message'=>'非法请求','code'=>'0']);
        }
    }


    //督办统计
    public function statistics(Request $request){

        $ser = new \app\admin\service\Supervision();

        if($request->isPost()){
            $param = $request->param();
            //dump($param);exit;
            $result = $ser->getStatistics($param);
            return show(1,'ok',$result);
        }else{
            $result = $ser->getStatistics();
        }

        $Department = \app\admin\model\Department::where('status',1)->select();
        return $this->fetch('',[
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param(),
            'department' => $Department,
            'result' => $result
        ]);
    }


    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['title']) && $filter['title']){
                $where['title'] = ['like', '%'.$filter['title'].'%'];
            }
            if(isset($filter['typeId']) && $filter['typeId']){
                $where['typeId'] = $filter['typeId'];
            }
            if(isset($filter['schedule']) && $filter['schedule']){
                $where['schedule'] = $filter['schedule'];
            }
        }

        return $where;
    }
}